using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameBoard : MonoBehaviour
{
    [Header("棋盘设置")]
    [SerializeField] private int boardSize = 15;
    [SerializeField] private float cellSize = 50f;
    [SerializeField] private GameObject linePrefab;
    [SerializeField] private GameObject piecePrefab;
    [SerializeField] private Transform boardParent;
    [SerializeField] private Transform pieceParent;

    [Header("棋子颜色")]
    [SerializeField] private Color blackColor = Color.black;
    [SerializeField] private Color whiteColor = Color.white;

    private PieceColor[,] board;
    private Dictionary<Vector2Int, GameObject> pieces = new Dictionary<Vector2Int, GameObject>();
    private bool isMyTurn = false;
    private PieceColor myColor = PieceColor.None;

    private void Awake()
    {
        InitializeBoard();
    }

    private void InitializeBoard()
    {
        board = new PieceColor[boardSize, boardSize];
        
        // 初始化棋盘数据
        for (int i = 0; i < boardSize; i++)
        {
            for (int j = 0; j < boardSize; j++)
            {
                board[i, j] = PieceColor.None;
            }
        }

        DrawBoard();
    }

    private void DrawBoard()
    {
        // 绘制横线
        for (int i = 0; i < boardSize; i++)
        {
            GameObject line = Instantiate(linePrefab, boardParent);
            RectTransform rt = line.GetComponent<RectTransform>();
            rt.anchoredPosition = new Vector2(0, i * cellSize - (boardSize - 1) * cellSize / 2);
            rt.sizeDelta = new Vector2((boardSize - 1) * cellSize, 2);
        }

        // 绘制竖线
        for (int i = 0; i < boardSize; i++)
        {
            GameObject line = Instantiate(linePrefab, boardParent);
            RectTransform rt = line.GetComponent<RectTransform>();
            rt.anchoredPosition = new Vector2(i * cellSize - (boardSize - 1) * cellSize / 2, 0);
            rt.sizeDelta = new Vector2(2, (boardSize - 1) * cellSize);
        }

        // 添加星位
        DrawStar(3, 3);
        DrawStar(3, 11);
        DrawStar(7, 7);
        DrawStar(11, 3);
        DrawStar(11, 11);
    }

    private void DrawStar(int row, int col)
    {
        GameObject star = new GameObject("Star");
        star.transform.SetParent(boardParent);
        Image image = star.AddComponent<Image>();
        image.color = Color.black;
        
        RectTransform rt = star.GetComponent<RectTransform>();
        rt.anchoredPosition = GetBoardPosition(row, col);
        rt.sizeDelta = new Vector2(8, 8);
    }

    private Vector2 GetBoardPosition(int row, int col)
    {
        float x = col * cellSize - (boardSize - 1) * cellSize / 2;
        float y = row * cellSize - (boardSize - 1) * cellSize / 2;
        return new Vector2(x, y);
    }

    public void OnBoardClick(Vector2 clickPosition)
    {
        if (!isMyTurn)
        {
            Debug.Log("不是你的回合");
            return;
        }

        // 转换点击位置到棋盘坐标
        Vector2Int boardPos = GetBoardCoordinate(clickPosition);
        
        if (boardPos.x < 0 || boardPos.x >= boardSize || boardPos.y < 0 || boardPos.y >= boardSize)
        {
            return;
        }

        if (board[boardPos.y, boardPos.x] != PieceColor.None)
        {
            Debug.Log("该位置已有棋子");
            return;
        }

        // 发送落子请求
        NetworkManager.Instance.PlacePiece(boardPos.y, boardPos.x);
    }

    private Vector2Int GetBoardCoordinate(Vector2 position)
    {
        float offsetX = (boardSize - 1) * cellSize / 2;
        float offsetY = (boardSize - 1) * cellSize / 2;
        
        int col = Mathf.RoundToInt((position.x + offsetX) / cellSize);
        int row = Mathf.RoundToInt((position.y + offsetY) / cellSize);
        
        return new Vector2Int(col, row);
    }

    public void PlacePiece(int row, int col, PieceColor color)
    {
        if (board[row, col] != PieceColor.None)
        {
            return;
        }

        board[row, col] = color;

        // 创建棋子
        GameObject piece = Instantiate(piecePrefab, pieceParent);
        RectTransform rt = piece.GetComponent<RectTransform>();
        rt.anchoredPosition = GetBoardPosition(row, col);
        
        Image image = piece.GetComponent<Image>();
        image.color = color == PieceColor.Black ? blackColor : whiteColor;

        pieces[new Vector2Int(col, row)] = piece;
    }

    public void SetGameInfo(string gameId, long playerId, PieceColor playerColor)
    {
        // 服务器已经存储了 gameId 和 playerId，客户端只需记录颜色
        myColor = playerColor;
    }

    public void SetMyTurn(bool isTurn)
    {
        isMyTurn = isTurn;
    }

    public void HighlightWinPositions(List<WinPosition> positions)
    {
        foreach (var pos in positions)
        {
            Vector2Int key = new Vector2Int(pos.Col, pos.Row);
            if (pieces.ContainsKey(key))
            {
                Image image = pieces[key].GetComponent<Image>();
                image.color = Color.red;
            }
        }
    }

    public void ResetBoard()
    {
        // 清除所有棋子
        foreach (var piece in pieces.Values)
        {
            Destroy(piece);
        }
        pieces.Clear();

        // 重置棋盘数据
        for (int i = 0; i < boardSize; i++)
        {
            for (int j = 0; j < boardSize; j++)
            {
                board[i, j] = PieceColor.None;
            }
        }

        isMyTurn = false;
        myColor = PieceColor.None;
    }
}
